<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 观察者模式，监控一个对象的状态，一旦状态发生变化，立马触发技能 -->
    <script>
        // 1、创建被观察者(属性，自己的状态、队列，记录都有谁观察自己、方法)
        // 2、创建观察者(一个身份证明、一个技能)

        //观察者构造函数
        class Observer {
            constructor(name, fn = () => {}) {
                this.name = name;
                this.fn = fn;
            }
        }
        //创建观察者
        let a = new Observer('one', () => {
            console.log("我是第一个观察者");
        });
        let b = new Observer('two', () => {
            console.log("我是第二个观察者");
        });

        //被观察者的构造函
        class Subject {
            constructor(state) {
                this.state = state;
                this.obeservers = [];
            };
            setState(val) {
                this.state = val;
                this.obeservers.forEach((item) => {
                    item.fn(this.state);
                })
            };
            addObserver(obs) {
                this.obeservers.push(obs);
            }
        }
    </script>
</body>

</html>